﻿using dotnet_graphql_demo.Model;
using GreenDonut;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace dotnet_graphql_demo.Infrastructure.Graphql
{
    public class OwnerDataLoader : BatchDataLoader<Guid, Owner>
    {
        private readonly IDbContextFactory<AppDbContext> _dbContextFactory;

        public OwnerDataLoader(
            IBatchScheduler batchScheduler,
            IDbContextFactory<AppDbContext> dbContextFactory)
            : base(batchScheduler)
        {
            _dbContextFactory = dbContextFactory ??
                throw new ArgumentNullException(nameof(dbContextFactory));
        }


        protected async override Task<IReadOnlyDictionary<Guid, Owner>> LoadBatchAsync(IReadOnlyList<Guid> keys, CancellationToken cancellationToken)
        {
            await using AppDbContext dbContext =
             _dbContextFactory.CreateDbContext();

            return await dbContext.Owners
             .Where(s => keys.Contains(s.Id))
             .ToDictionaryAsync(t => t.Id, cancellationToken);
        }
    }
}
